package com.zj.musicTools.function

import android.content.Intent
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat.startActivity
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionStatus
import com.google.accompanist.permissions.rememberPermissionState

lateinit var perhandler: getPermission

@Composable
fun PermissionPage() {
//    getPermission.PermissionPageContent()
    perhandler = getPermission()
    perhandler.checkStorageManagerPermission()
}

class getPermission {
    val allFile = mutableStateOf(false)
//    var perhandler: getPermission


    @OptIn(ExperimentalPermissionsApi::class)
    @Composable
    fun PermissionPageContent(): Int {
        //当前需要申请的权限
        val myPermissionState = rememberPermissionState(
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE //写权限

        )
        var state = -1

        when (myPermissionState.status) {
            PermissionStatus.Granted -> {//已授权
                Text("Camera permission Granted")
                state = 1
            }
            is PermissionStatus.Denied -> {
                Column {
                    var textToShow = ""
                    if ((myPermissionState.status as PermissionStatus.Denied).shouldShowRationale) {
                        //如果用户拒绝了该权限但可以显示理由，那么请温和地解释为什么应用程序需要此权限(拒绝权限)
                        textToShow =
                            "The camera is important for this app. Please grant the permission."
                        state = -1
                    } else {
                        //如果这是用户第一次登陆此功能，或者用户不想再次被要求获得此权限，请说明该权限是必需的(用户选择拒绝且不再询问)
                        textToShow =
                            "Camera permission required for this feature to be available. " +
                                    "Please grant the permission"
                        state = 0
                    }
                    Text(textToShow)
                    Button(onClick = {
                        //申请权限
                        myPermissionState.launchPermissionRequest()
                    }) {
                        Text("Request permission")
                    }
                }
            }
        }
        return state
    }

    @Composable
    fun permissionActivity() {
        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)//访问所有文件的权限
        startActivity(LocalContext.current, intent, null)
    }


    @Composable
    fun checkStorageManagerPermission() {
/*    Text(text = "Compose Text")
//    var mycontext:Context
    AndroidView(factory = { context ->
        //这里也可以使用LayoutInflater从xml中解析出一个View
//        mycontext=context
        TextView(context).apply {
            text = "传统TextView"
        }})*/


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
            Environment.isExternalStorageManager()
        ) {
            Toast.makeText(LocalContext.current, "已获得访问所有文件权限", Toast.LENGTH_SHORT).show()
            allFile.value=true
            return
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            Toast.makeText(LocalContext.current, "另外获得访问所有文件权限", Toast.LENGTH_SHORT).show()
        } else {
            /*var checkpermiss=false
        val builder = AlertDialog.Builder(LocalContext.current)
            .setMessage("本程序需要您同意允许访问所有文件权限")
            .setPositiveButton("确定") { _, _ ->
                checkpermiss=true
                builderOnClick()
            }
        builder.show()*/
            val buttonVal = remember { mutableStateOf(false) }
            val openDialog = remember { mutableStateOf(true) }//控制关闭弹窗
            if (buttonVal.value) {
                 permissionActivity()
            }
            if(openDialog.value) AlertDialog(onDismissRequest = { buttonVal.value = false },
                text = { Text("本程序需要您同意允许访问所有文件权限") },
                confirmButton = { TextButton(onClick = { buttonVal.value = true
                                                        openDialog.value=false}) { Text("确认") } },
                dismissButton = { TextButton(onClick = { buttonVal.value = false
                                                        openDialog.value=false}) { Text("取消") } }
            )
        }
    }
}
/**
 * https://blog.csdn.net/XL1583135614/article/details/124170857
 * https://zhuanlan.zhihu.com/p/535741380
 *
 *
 * 目前会弹出页面设置访问权限，可访问输入文件。
 * 后期思路：使用try……result的形式运行转换，如果遇到权限报错，就弹出权限申请。
 *
* */
/*


//获取存储权限
private fun getPermissions() {
//        普通权限：只需要在清单文件中注册即可
//        危险权限(Android 6.0 之后)：需要在代码中动态申请，以弹系统 Dialog 的形式进行请求
//        特殊权限(Android 11(含) 之后)：需要在代码中动态申请，以跳系统 Activity 的形式进行请求
    //android版本大于等于11
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //必须要MANAGE_EXTERNAL_STORAGE权限，但Google Play Console审核不通过
        // 先判断有没有权限
        if (Environment.isExternalStorageManager()) {
            Thread(saveFileRunnable).start()
        } else {
            val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.data = Uri.parse("package:" + getPackageName())
            startActivityForResult(intent, 0)
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(
                ApplicationProvider.getApplicationContext<Context>(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            //存储空间权限
            requestPermissions(arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
        } else {
            //有权限后需要处理的功能
        }
    } else {
        //有权限后需要处理的功能
    }
}

// 提示是否獲取存储空间权限
fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String?>?,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    when (requestCode) {
        0 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 取得权限
            //有权限后需要处理的功能
        } else { // 未取得权限
            Toast.makeText(
                ApplicationProvider.getApplicationContext(),
                getString(R.string.language_noPermissions),
                Toast.LENGTH_SHORT
            ).show()
        }
    }
}

//Android 11以上(含)同意存储权限直接保存图片
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        if (Environment.isExternalStorageManager()) {
            //有权限后需要处理的功能
        } else {
            Toast.makeText(
                ApplicationProvider.getApplicationContext(),
                getString(R.string.language_noPermissions),
                Toast.LENGTH_SHORT
            ).show()
        }
    }
}*/
